package com.starking.wxx.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @描述: 微信自动参与抽奖【小程序】
 * @文件名: AutoAward.java
 * @创建人: wangxinxin
 * @创建时间: 2018/11/8
 * @修改人: wangxinxin
 * @修改备注: <br/>
 * <p>
 */
public class AutoAward {
    public static final Logger LOGGER = LoggerFactory.getLogger(AutoAward.class);

    //参与失败的活动id集合
    private static Set<String> failActSet = new HashSet<>(2048);

    private static String list_url = "https://lucky.nocode.com/public_lottery?size=5&page=";
    private static String join_url = "https://lucky.nocode.com/lottery/id/join";

//    static String auth = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjQxNDc2Nywibmlja19uY" +
//            "W1lIjoi5Zyf6LGq6YeR55qE5YWt5qyh5pa5IiwiYXZhdGFyIjoiaHR0cHM6Ly93eC5xbG9nby5jbi9tbW9wZW4vdmlf" +
//            "MzIvOFZoSDBSa0JwTVg2elZxRDFjcG9hZEZxY2ZER3ZHV09EYUczU2hsaWJWcTNpY1cycEk3SmtCUVVRMGliZUhrUURjTzZiRU" +
//            "U2RnFrMmZFZDJkc2xkWFp3VWcvMCIsInByb3ZpbmNlIjoiIiwiY2l0eSI6IiIsImdlbmRlciI6IjAiLCJpYXQiOjE1NDE2NzczNzQsImV" +
//            "4cCI6MTU0MjI4MjE3NH0.Lr3fOUI2KyAi64Sk1fmjJhJU0IB2YhNFnnArhTNWKcQ";

//    static String qiyu_auth = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMzM4MzczMTYsIm5pY2tfbmFtZSI6IlJhY2hlbCIsImF2YXRhciI6Imh0dHBzOi8vd3gucWxvZ28uY24vbW1vcGVuL3ZpXzMyL3FpY1hLYjIycmlhaWNaVUV6WmZYelJQRllCSkM5ZVU0aWNPRWxpY24wSFJ1a3BqMnROaWJkeEx0Zmt5SjFBNFBhcU15TGlhcHFpYnBiRjM3S2xDbWlhbTdQN1JwV2FBLzEzMiIsInByb3ZpbmNlIjoiIiwiY2l0eSI6IiIsImdlbmRlciI6IjIiLCJpYXQiOjE1NDE2ODIxMTUsImV4cCI6MTU0MjI4NjkxNX0.wKG1K0773CZOz6OndeyGgsJu_7r4cd5yef5Q0Nxhlj8";


    /**
     * 查询活动列表
     *
     * @param auth 认证信息
     * @param page 页数
     * @return
     */
    public static List<WeixinPriceAct> queryAwardActList(String auth, int page) {
        List<WeixinPriceAct> actList = new ArrayList<>();//抽奖活动列表

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String getUrl = list_url + page;
        HttpGet httpGet = new HttpGet(getUrl);
        LOGGER.info("getUrl = {}", getUrl);

        //设置认证
        httpGet.addHeader("Authorization", auth);
        LOGGER.info("auth = {}", auth);

        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            LOGGER.info("result = {}", resultString);

            JSONObject jsonObject = JSON.parseObject(resultString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String id = jsonObject1.getString("id");
                String joined = jsonObject1.getString("joined");

                WeixinPriceAct act = new WeixinPriceAct(id, joined);
                actList.add(act);
            }

        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("query act list is error!!!", e);
        }finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return actList;
    }

    /**
     *  自动参加某个抽奖活动
     * @param auth  认证
     * @param actId 活动id
     * @return
     */
    public static boolean autoJoinAct(String auth, String actId) {

        //已参与并且失败，不再参与
        if (failActSet.contains(actId)) {
            LOGGER.info("join act has fail! actid = {}", actId);
            return false;
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = join_url;
        url = url.replace("id", actId);
        LOGGER.info("join act url = {}", url);

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Authorization", auth);
        LOGGER.info("auth = {}", auth);

        try {
            CloseableHttpResponse result = httpclient.execute(httpPost);
            String resultstr = EntityUtils.toString(result.getEntity(), "utf-8");
            LOGGER.info("join result = {}", resultstr);

            JSONObject jsonObject2 = JSON.parseObject(resultstr);
            String data = jsonObject2.getString("data");
            if (!StringUtils.isEmpty(data)) {
                LOGGER.info("参与抽奖成功！actid = {}", actId);
                return true;
            }else{
                LOGGER.info("参与抽奖失败！actid = {}", actId);
                //存储失败集合
                failActSet.add(actId);
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


   public static class WeixinPriceAct {
        private String id;//奖品ID
        private String joined;//是否参加

        public WeixinPriceAct() {
        }

        public WeixinPriceAct(String id, String joined) {
            this.id = id;
            this.joined = joined;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getJoined() {
            return joined;
        }

        public void setJoined(String joined) {
            this.joined = joined;
        }
    }

//    public static void main(String[] args) {
//        auth = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjQxNDc2NywiaWF0IjoxNTQ1MTQwODY2LCJleHAiOjE1NDU3NDU2NjZ9.WxrDpB2vspXzcPcuafdx407geDSos7yD9R8l861uxG4";
//
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//
//        HttpGet httpGet = new HttpGet(list_url + 1);
////        HttpPost httpPost = new HttpPost(list_url);
//        httpGet.addHeader("Authorization", auth);
//
//        try {
//            CloseableHttpResponse response = httpclient.execute(httpGet);
//            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//
//            System.out.println("list result = " + resultString);
//            JSONObject jsonObject = JSON.parseObject(resultString);
//            JSONArray jsonArray = jsonObject.getJSONArray("data");
//           /* for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                String id = jsonObject1.getString("id");
//                System.out.println("id = " + id);
//                String url = join_url;
//                url = url.replace("id", id);
//                HttpPost httpPost = new HttpPost(url);
//                httpPost.addHeader("Authorization", auth);
//                CloseableHttpResponse result = httpclient.execute(httpPost);
//                String resultstr = EntityUtils.toString(result.getEntity(), "utf-8");
//                JSONObject jsonObject2 = JSON.parseObject(resultstr);
//                String data = jsonObject2.getString("data");
//                if (!StringUtils.isEmpty(data)) {
//                    System.out.println("抽奖成功一次！");
//                }else{
//                    System.out.println(resultstr);
//                }
//            }*/
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
